package com.inspectortime.webapp.util;

import javax.servlet.http.HttpServletRequest;

public class RequestPathUtils {

	private RequestPathUtils() {
	}

	public static final String INSPECTORS_PATH_SEGMENT_NAME = "inspectors";

	public static final String INSPECTOR_PATH_SEGMENT_NAME = "inspector";

	public static final String DEFAULT_INSPECTORS_VIEW_FOLDER = "default";
	
	public static final String ACTIONABLE_EXTENSION = ".html";

	/**
	 * Extract the [inspectorShortName] part of a
	 * /context/inspectors/[inspectorShortName]/somePath.html path
	 * 
	 * @param request
	 * @return The inspector company short name if path matches the right
	 *         pattern, otherwise null.
	 */
	public static String extractInspectorCompanyShortNameFromPath(
			HttpServletRequest request) {
		String[] parts = request.getServletPath().split("/");
		if (parts.length == 4 && parts[1].equals(INSPECTORS_PATH_SEGMENT_NAME)) {
			
			if (!parts[2].equals(DEFAULT_INSPECTORS_VIEW_FOLDER)) {
				return parts[2];	
			}			
		}

		return DEFAULT_INSPECTORS_VIEW_FOLDER;
	}
	
	public static boolean isProtectedPath(
			HttpServletRequest request) {
		String[] parts = request.getServletPath().split("/");
		if (parts.length > 1 && parts[1].equals(INSPECTOR_PATH_SEGMENT_NAME)) {
			return true;
		}

		return false;
	}

	/**
	 * @param request
	 * @return
	 */
	public static String extractRemainingPath(HttpServletRequest request) {
		String[] parts = request.getServletPath().split("/");
		return parts[parts.length - 1];
	}
	
	/**
	 * Strip the leading slash and trailing ".xxx" to get view name
	 * @param request
	 * @return
	 */
	public static String extractViewNameFromPath(HttpServletRequest request) {
		String servletPath = request.getServletPath();
		String viewName = servletPath.substring(1, servletPath.length()
						- (ACTIONABLE_EXTENSION.length()));
		return viewName;
	}
	
	/**
	 * Get the http://www.inspectortime.com starting part of a URL
	 * @param req
	 * @return
	 */
	public static String extractSchemeAndRemoteHost(HttpServletRequest req) {
		String scheme = req.getScheme();             // http
        String serverName = req.getServerName();     // hostname.com
        int serverPort = req.getServerPort();        // 80
        
        if (serverPort == 80 && serverPort == 443) {
        	return scheme+"://"+serverName;
        }
        return scheme+"://"+serverName+":"+serverPort;
	}
	
	public static String extractWebappUrl(HttpServletRequest req) {
		String contextPath = req.getContextPath();   // /mywebapp
		return extractSchemeAndRemoteHost(req) + "/" + contextPath;
	}
	
	public static String constructLogoUrl(HttpServletRequest req, String companyShortName) {
		String webappUrl = extractWebappUrl(req);
		return webappUrl + "/inspectors/logo-image/" + companyShortName + ".html";
	}
}
